home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 5817 / 5817.xpi / chrome / content / workerCsv.js < prev   
Encoding:
Text File  |  2010-02-11  |  8.2 KB  |  269 lines

  1. var gStage = 0;
  2.  
  3. var tempStore = {
  4.   csvParams: null,
  5.   csvRecords: null,
  6.   columns: [],
  7.   queries: []
  8. };
  9.  
  10. onmessage = function(event) {
  11.   if (event.data) {
  12.     var params = event.data;
  13.     gStage = params.stage;
  14.     postMessage('Processing csv import stage ' + gStage);
  15.     switch (gStage) {
  16.     case 1:
  17.       var obj = readCsvContent(params);
  18.       postMessage(obj);
  19.       break;
  20.     case 2:
  21.       var obj = createAllQueries(params);
  22.       postMessage(obj);
  23.       break;
  24.     }
  25.   }
  26. };
  27.  
  28. function readCsvContent(csvParams) {
  29.   tempStore.csvParams = csvParams;
  30.  
  31.   var sData = readFile(csvParams.file, csvParams.charset);
  32.   postMessage('Read csv file: ' + sData.length + ' bytes');
  33.   tempStore.csvRecords = CsvToArray(sData, csvParams.separator);
  34.  
  35.   var iRows = tempStore.csvRecords.length;
  36.   postMessage('Parsed csv data: ' + iRows + ' records');
  37.  
  38.   if (iRows <= 0) {
  39.     var obj = {stage: gStage, success: 0, description: 'no rows found'};
  40.     return obj;
  41.   }
  42.  
  43.   tempStore.columns = [];
  44.   var aVals = tempStore.csvRecords[0];
  45.   if (csvParams.bColNames) {
  46.     for (var c = 0; c < aVals.length; c++) {
  47.       tempStore.columns.push(aVals[c]);
  48.     }
  49.   }
  50.   else {
  51.     for (var c = 1; c <= aVals.length; c++)
  52.       tempStore.columns.push("col_" + c);
  53.   }
  54.  
  55.   var obj = {stage: gStage, success: 1, description: '', tableName: csvParams.tableName, columns: tempStore.columns};
  56.   return obj;
  57. }
  58.  
  59. function createAllQueries(params) {
  60.   var aQueries = [];
  61.   var iOtherQueries = 0;
  62.   if (params.createTableQuery != "") {
  63.     aQueries.push(params.createTableQuery);
  64.      iOtherQueries = 1;
  65.   }
  66.  
  67.   var iRows = tempStore.csvRecords.length;
  68.   var iCols = tempStore.columns.length;
  69.   var bColNames = tempStore.csvParams.bColNames;
  70.  
  71.   var sQuery = "";
  72.  
  73.   for (var i = bColNames?1:0; i < iRows; i++) {
  74.     var aVals = tempStore.csvRecords[i];
  75.  
  76.     var iCol = 0;
  77.     var aInp = [];
  78.     var aBadLines = [];
  79.     var sNoValue = "''";
  80.     for (var c = 0; c < aVals.length; c++) {
  81.       if (aVals[c] != null)
  82.         aVals[c] = quote(aVals[c]);
  83.       else
  84.         aVals[c] = "null";
  85.  
  86.       aInp.push(aVals[c]);
  87.     }
  88.     
  89.     //if aInp has fewer values than expected, 
  90.     //complete the aInp array with empty strings.
  91.     while (aInp.length < iCols)
  92.       aInp.push(sNoValue);
  93.  
  94.     //aBadLines will not be empty only if their are more values than columns
  95.     if (aInp.length != iCols) {
  96.       aBadLines.push(i+1);
  97.       continue;
  98.     }
  99.     sVals = " VALUES (" + aInp.join(",") + ")";
  100.     sQuery = "INSERT INTO " + params.tableName + sVals;
  101.     aQueries.push(sQuery);
  102.     postMessage('Creating SQL statements: ' + aQueries.length + ' created');
  103.   }
  104.   var num = aQueries.length - iOtherQueries;
  105.   var obj = {stage: gStage, success: 1, description: '', numRecords: num, queries: aQueries, badLines: aBadLines};
  106.   return obj;
  107. }
  108.  
  109. function readFile(file, charset) {
  110.   var req = new XMLHttpRequest();
  111.   req.open('GET', file, false);
  112.   req.overrideMimeType('text/plain; charset='+charset);
  113.   req.send(null);
  114.   if(req.status == 0)
  115.     return req.responseText;
  116. }
  117.  
  118. //When there are 2 consecutive separators (,,) or a separator at the start of a line (^,) we treat them as having a null field in between. If separator is followed by newline (,\n) the treatment depends upon user option whether to ignore trailing commas. If not ignored, a null field is assumed after the trailing delimiter. However, lines which have no character in them (^\n) are ignored instead of the possible alternative of treating them as representative of a single null field. See Issue #324 too.
  119. function CsvToArray(input, separator) {
  120.   var re_linebreak = /[\n\r]+/
  121.  
  122.   var re_token = /[\"]([^\"]|(\"\"))*[\"]|[,]|[\n\r]|[^,\n\r]*|./g
  123.   if (separator == ";")
  124.     re_token = /[\"]([^\"]|(\"\"))*[\"]|[;]|[\n\r]|[^;\n\r]*|./g
  125.   if (separator == "|")
  126.     re_token = /[\"]([^\"]|(\"\"))*[\"]|[|]|[\n\r]|[^|\n\r]*|./g
  127.   if (separator == "\t")
  128.     re_token = /[\"]([^\"]|(\"\"))*[\"]|[\t]|[\n\r]|[^\t\n\r]*|./g
  129.  
  130.   //TODO: try using exec in a loop
  131.   var a = input.match(re_token);
  132.  
  133.   var token;
  134.   var line = [], allLines = [];
  135.   var tkSEPARATOR = 0, tkNEWLINE = 1, tkNORMAL = 2;
  136.   var tk = tkNEWLINE, tkp = tkNEWLINE;
  137.  
  138.   for (var i = 0; i < a.length; i++) {
  139.     tkp = tk;
  140.  
  141.     token = a[i];
  142.     
  143.     if (token == separator) {
  144.       tk = tkSEPARATOR;
  145.       //this separator is the first char in line or follows another separator
  146.       if (line.length == 0 || tkp == tkSEPARATOR) {
  147.         line.push(null);
  148.       }
  149.     }
  150.     else if (token == "\n" || token == "\r") {
  151.       tk = tkNEWLINE;
  152.       if (!tempStore.csvParams.ignoreTrailingDelimiter && tkp == tkSEPARATOR) {
  153.         line.push(null);
  154.       }
  155.       if (line.length > 0) {
  156.         allLines.push(line);
  157.         postMessage('Parsing csv data: ' + allLines.length + ' records');
  158.         line = [];
  159.       }
  160.     }
  161.     else { //field value
  162.       tk = tkNORMAL;
  163.       if (tkp != tkSEPARATOR) {
  164.         if (line.length > 0) {
  165.           allLines.push(line);
  166.           postMessage('Parsing csv data: ' + allLines.length + ' records');
  167.           line = [];
  168.         }
  169.       }
  170.       //remove quotes from both ends
  171.       if (token.length >= 2) {
  172.         var firstChar = token[0];
  173.         if (firstChar == '"' || firstChar == "'") {
  174.           if (token[token.length - 1] == firstChar) {
  175.             token = token.substring(1, token.length - 1);
  176.           }
  177.         }
  178.       }
  179.       line.push(token);
  180.     }
  181.   }
  182.  
  183.   return allLines;
  184. }
  185.  
  186. //http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
  187. function CsvToArray1(strData, strDelimiter) {
  188.   // Check to see if the delimiter is defined. If not,
  189.   // then default to comma.
  190.   strDelimiter = (strDelimiter || ",");
  191.  
  192.   // Create a regular expression to parse the CSV values.
  193.   var objPattern = new RegExp(
  194.     (  // Delimiters.
  195.       "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
  196.       // Quoted fields.
  197.       "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
  198.       // Standard fields.
  199.       "([^\"\\" + strDelimiter + "\\r\\n]*))"
  200.     ), "gi");
  201.  
  202.   // Create an array to hold our data. Give the array
  203.   // a default empty first row.
  204.   var arrData = [[]];
  205.  
  206.   // Create an array to hold our individual pattern
  207.   // matching groups.
  208.   var arrMatches = null;
  209.  
  210.   // Keep looping over the regular expression matches
  211.   // until we can no longer find a match.
  212.   while (arrMatches = objPattern.exec(strData)) {
  213.  
  214.     // Get the delimiter that was found.
  215.     var strMatchedDelimiter = arrMatches[1];
  216.      postMessage('delim: ' + arrData.length + ':' + strMatchedDelimiter);
  217.  
  218.     // Check to see if the given delimiter has a length
  219.     // (is not the start of string) and if it matches
  220.     // field delimiter. If id does not, then we know
  221.     // that this delimiter is a row delimiter.
  222.     if (strMatchedDelimiter.length &&
  223.       (strMatchedDelimiter != strDelimiter)) {
  224.  
  225.       // Since we have reached a new row of data,
  226.       // add an empty row to our data array.
  227.       arrData.push([]);
  228.       postMessage('Parsing csv data: ' + arrData.length + ' records');
  229.     }
  230.  
  231.     // Now that we have our delimiter out of the way,
  232.     // let's check to see which kind of value we
  233.     // captured (quoted or unquoted).
  234.     if (arrMatches[2]) {
  235.  
  236.       // We found a quoted value. When we capture
  237.       // this value, unescape any double quotes.
  238.       var strMatchedValue = arrMatches[2].replace(
  239.         new RegExp("\"\"", "g" ), "\"");
  240.      postMessage('value q: ' + arrData.length + ':' + strMatchedValue);
  241.     }
  242.     else {
  243.  
  244.       // We found a non-quoted value.
  245.       var strMatchedValue = arrMatches[3];
  246.      postMessage('value nq: ' + arrData.length + ':' + strMatchedValue);
  247.  
  248.       //next two lines by mkt to distinguish null from strings
  249.       if (strMatchedValue == undefined || strMatchedValue == null)
  250.         strMatchedValue = null;
  251.       else
  252.       if (strMatchedValue.length == 0)
  253.         strMatchedValue = null;
  254.     }
  255.  
  256.     // Now that we have our value string, let's add
  257.     // it to the data array.
  258.     arrData[arrData.length - 1].push(strMatchedValue);
  259.      postMessage('value: ' + arrData.length + ':' + strMatchedValue);
  260.   }
  261.  
  262.   // Return the parsed data.
  263.   return arrData;
  264. }
  265.  
  266. function quote(str) {
  267.   if (typeof str == "string")
  268.     str = str.replace("'", "''", "g");
  269.   return "'" + str + "'";
  270. }
  271.  
  272.